package com.example.demo.controller;

import com.example.demo.entity.Cart;
import com.example.demo.entity.CartPage;
import com.example.demo.util.KafkaUtils;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiImplicitParam;
import io.swagger.annotations.ApiImplicitParams;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.web.bind.annotation.*;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.concurrent.TimeUnit;

@RestController
@Slf4j
@Api(value = "购物车controller",tags = "Redis购物车接口（用户已登录）")
@RequestMapping("/cart/redis")
public class RedisUserCartController{

    @Autowired
    private RedisTemplate redisTemplate;

    @Autowired
    private KafkaUtils kafkaUtils;

    //购物车key的前缀
    public static final String CART_KEY = "cart:user:";

    //添加购物车
    @ResponseBody
    @RequestMapping(value = "/addCart", method = RequestMethod.POST)
    @ApiOperation(value = "添加购物车",httpMethod = "POST")
    @ApiImplicitParams({@ApiImplicitParam(name = "userId",value = "用户id",dataType = "Long",paramType = "query"),
            @ApiImplicitParam(name = "menuId",value = "菜单id",dataType = "Long",paramType = "query"),
            @ApiImplicitParam(name = "number",value = "数量",dataType = "int",paramType = "query")})
    public void addCart(@RequestParam("userId") Long userId,
                        @RequestParam("menuId") Long menuId,
                        @RequestParam("number") Integer number){
        String key = CART_KEY + userId;
        //获取key是否存在
        Boolean hasKey = redisTemplate.opsForHash().getOperations().hasKey(key);

        if(hasKey){
            this.redisTemplate.opsForHash().put(key, menuId.toString(), number);
        }else {
            this.redisTemplate.opsForHash().put(key, menuId.toString(), number);
            //设置90天过期
            this.redisTemplate.expire(key,90, TimeUnit.DAYS);
        }

        //存入数据库请求参数
        String sqlMessage = "CartAdd,"+userId+","+ menuId +","+number;
        //TODO 发 rabbitmq 出去
        kafkaUtils.sendMessage("topic1",sqlMessage);
    }

    //修改购物车
    @ResponseBody
    @RequestMapping(value = "/updateCart", method = RequestMethod.POST)
    @ApiOperation(value = "更新购物车菜品数",httpMethod = "POST")
    @ApiImplicitParams({@ApiImplicitParam(name = "userId",value = "用户id",dataType = "Long",paramType = "query"),
            @ApiImplicitParam(name = "menuId",value = "菜单id",dataType = "Long",paramType = "query"),
            @ApiImplicitParam(name = "number",value = "数量",dataType = "int",paramType = "query")})
    public void updateCart(@RequestParam("userId") Long userId,
                           @RequestParam("menuId") Long menuId,
                           @RequestParam("number") Integer number){
        String key = CART_KEY + userId;
        this.redisTemplate.opsForHash().put(key, menuId.toString(), number);

        //存入数据库请求参数
        String sqlMessage = "updateCart,"+userId+","+ menuId +","+number;
        //TODO 发 rabbitmq 出去
        kafkaUtils.sendMessage("topic1",sqlMessage);
    }

    //删除菜品
    @ResponseBody
    @RequestMapping(value = "/delCart",method = RequestMethod.POST)
    @ApiOperation(value = "删除菜品",httpMethod = "POST")
    @ApiImplicitParams({@ApiImplicitParam(name = "userId",value = "用户id",dataType = "Long",paramType = "query")})
    public void delCart(Long userId, Long menuId){
        String key = CART_KEY + userId;
        this.redisTemplate.opsForHash().delete(key, menuId.toString());

        //存入数据库请求参数
        String sqlMessage = "delCart,"+userId+","+ menuId;
        //TODO 发 rabbitmq 出去
        kafkaUtils.sendMessage("topic1",sqlMessage);
    }


    @RequestMapping(value = "/findAll",method = RequestMethod.GET)
    @ApiOperation(value = "查询购物车",httpMethod = "GET")
    @ApiImplicitParams({@ApiImplicitParam(name = "userId",value = "用户id",dataType = "Long",paramType = "query")})
    public CartPage findAll(Long userId){
        String key = CART_KEY + userId;
        CartPage cartPage = new CartPage();
        //查购物车的总数
        long size = this.redisTemplate.opsForHash().size(key);
        cartPage.setCount((int) size);

        //查询购物车的所有商品
        Map<String, Integer> map = this.redisTemplate.opsForHash().entries(key);
        List<Cart> cartList = new ArrayList<>();
        for (Map.Entry<String, Integer>entry : map.entrySet()){
            Cart cart = new Cart();
            cart.setUserId(userId);
            cart.setMenuId(Long.parseLong(entry.getKey()));
            cart.setNumber(entry.getValue());
            cartList.add(cart);
        }
        cartPage.setCartList(cartList);
        return cartPage;

    }


}
